<template>
  <!-- 关联任务模板对话框 -->
  <el-dialog
    :title="'选择任务模板'"
    v-model="open"
    width="70%"
    :close-on-click-modal="false"
    append-to-body
    v-loading="loading"
  >
    <el-form
      :model="selectParams"
      ref="selectForm"
      :inline="true"
      label-width="100px"
      class="form-search"
    >
      <el-form-item label="任务模板名称" prop="templateName">
        <el-input v-model="selectParams.templateName" placeholder="请输入任务模板名称" clearable />
      </el-form-item>
      <el-form-item label="表单名称" prop="reportName">
        <el-input v-model="selectParams.reportName" placeholder="请输入表单名称" clearable />
      </el-form-item>
      <el-form-item label="类型" prop="templateType">
        <el-select v-model="selectParams.templateType" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in task_template_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="selectParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in task_template_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleSelectQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetSelectQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="selectLoading"
      :data="selectList"
      border
      @select="handleSelectionChange"
      @select-all="selectAll"
      show-overflow-tooltip
      ref="taskTemplateTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="任务模板编号" align="center" prop="templateCode" />
      <el-table-column label="任务模板名称" align="center" prop="templateName" />
      <el-table-column label="模板类型" align="center" prop="templateType">
        <template #default="scope">
          <dict-tag :options="task_template_type" :value="scope.row.templateType" />
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="报表名称" align="center" prop="reportName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="task_template_status" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="selectTotal > 0"
      :total="selectTotal"
      v-model:page="selectParams.pageNum"
      v-model:limit="selectParams.pageSize"
      @pagination="getSelectList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="taskTemplate">
import { listTaskTemplate } from "@/api/technology/taskTemplate";
import { addTechProcessTaskTemplate } from "@/api/technology/processManage";
import { ref, reactive, toRefs, getCurrentInstance, watch, nextTick } from "vue";
const props = defineProps(["processId", "processManageId", "openTaskTemplate"]);
const { processId, processManageId, openTaskTemplate } = toRefs(props);
const open = ref(false);
const selectLoading = ref(true);
const selectTotal = ref(0);
const selectList = ref([]);
const emit = defineEmits(["change"]);
const taskTemplateTable = ref();
const loading = ref(false);
const data = reactive({
  form: {},
  selectParams: {
    pageNum: 1,
    pageSize: 10,
    status: "TASK_TEMPLATE_STATUS_ENABLE",
  },
});
// const selectable = (row) => row.status == "0";
const { selectParams } = toRefs(data);
const arrInfoSelection = ref([]);
const { proxy } = getCurrentInstance();
const { task_template_status } = proxy.useDict("task_template_status");
const { task_template_type } = proxy.useDict("task_template_type");

watch(
  openTaskTemplate,
  (val) => {
    open.value = val;
    arrInfoSelection.value = [];
    getSelectList();
  },
  { immediate: true, deep: true }
);

// watch(
//   () => processId.value,
//   (newValue) => {
//     if (newValue) {
//     }
//   },
//   {
//     immediate: true,
//   }
// );
function getSelectList() {
  selectLoading.value = true;
  listTaskTemplate(selectParams.value).then((response) => {
    selectList.value = response.rows;
    selectTotal.value = response.total;
    selectLoading.value = false;
    nextTick(() => {
      if (selectList.value.length && arrInfoSelection.value.length) {
        selectList.value.forEach((item) => {
          const include = arrInfoSelection.value.filter((info) => info.id == item.id);
          if (include.length) {
            taskTemplateTable.value.toggleRowSelection(item, true);
          } else {
            taskTemplateTable.value.toggleRowSelection(item, false);
          }
        });
      }
    });
  });
}

// 取消按钮
function cancel() {
  emit("changeTemplateDialogList", "");
}

/** 搜索按钮操作 */
function handleSelectQuery() {
  selectParams.value.pageNum = 1;
  getSelectList();
}
/** 重置按钮操作 */
function resetSelectQuery() {
  proxy.resetForm("selectForm");
  handleSelectQuery();
}
/** 选择条数  */
function handleSelectionChange(selection, row) {
  let selected = selection.length && selection.indexOf(row) !== -1;
  if (selected) {
    arrInfoSelection.value.push(row);
  } else {
    arrInfoSelection.value = arrInfoSelection.value.filter((item) => item.id != row.id);
  }
}

// 全选 或全不选
function selectAll(section) {
  if (section.length) {
    // 全选  push
    section.forEach((item) => {
      arrInfoSelection.value.push(item);
    });
  } else {
    // 全不选  当页数据  删除
    if (selectList.value.length && arrInfoSelection.value.length) {
      selectList.value.forEach((item) => {
        arrInfoSelection.value = arrInfoSelection.value.filter((info) => item.id != info.id);
      });
    }
  }
  arrInfoSelection.value = uniqueObjects(arrInfoSelection.value);
}

/** 提交按钮 */
function submitForm() {
  loading.value = true;
  console.log(arrInfoSelection.value, "=====arrInfoSelection========");
  let params = [];
  for (let i in arrInfoSelection.value) {
    params.push({
      workProcedureId: processId.value,
      processManageId: processManageId.value,
      taskTemplateId: arrInfoSelection.value[i].id,
    });
  }

  addTechProcessTaskTemplate(params)
    .then(() => {
      proxy.$modal.msgSuccess("新增任务模板成功");
      loading.value = false;
      emit("changeTemplateDialogList", "update");
    })
    .catch(() => {
      loading.value = false;
    });
}

// 数组对象去重
function uniqueObjects(arr) {
  const seen = new Map();
  return arr.filter((item) => {
    // 将对象转换为字符串（或其他可以唯一表示对象的内容）
    const key = JSON.stringify(item);
    // 如果 Map 中还没有这个键，则添加它并返回 true
    if (!seen.has(key)) {
      seen.set(key, item);
      return true;
    }
    // 如果已经有了，就返回 false，表示这个对象应该被过滤掉
    return false;
  });
}
</script>
